package com.dong.oss.controller;

import com.dong.oss.dto.MigrationRequest;
import com.dong.oss.dto.MigrationResult;
import com.dong.oss.service.MigrationService;
import com.dong.oss.service.MinioService;
import com.dong.oss.service.OssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 迁移控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/migration")
@RequiredArgsConstructor
public class MigrationController {
    
    private final MigrationService migrationService;
    private final MinioService minioService;
    private final OssService ossService;
    
    /**
     * 执行迁移
     * 
     * @param request 迁移请求
     * @return 迁移结果
     */
    @PostMapping("/migrate")
    public ResponseEntity<MigrationResult> migrate(@RequestBody MigrationRequest request) {
        log.info("收到迁移请求: {}", request);
        
        try {
            MigrationResult result = migrationService.migrate(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("迁移请求处理失败", e);
            MigrationResult errorResult = MigrationResult.builder()
                    .success(false)
                    .errorMessage(e.getMessage())
                    .build();
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    /**
     * 快速迁移所有文件
     * 
     * @return 迁移结果
     */
    @PostMapping("/migrate-all")
    public ResponseEntity<MigrationResult> migrateAll() {
        log.info("收到快速迁移所有文件请求");
        
        MigrationRequest request = MigrationRequest.builder()
                .overwrite(false)
                .imageOnly(false)
                .build();
        
        return migrate(request);
    }
    
    /**
     * 快速迁移所有图片文件
     * 
     * @return 迁移结果
     */
    @PostMapping("/migrate-images")
    public ResponseEntity<MigrationResult> migrateImages() {
        log.info("收到快速迁移所有图片文件请求");
        
        MigrationRequest request = MigrationRequest.builder()
                .overwrite(false)
                .imageOnly(true)
                .build();
        
        return migrate(request);
    }
    
    /**
     * 获取MinIO文件列表
     * 
     * @param prefix 文件前缀（可选）
     * @return 文件列表
     */
    @GetMapping("/minio/objects")
    public ResponseEntity<Map<String, Object>> getMinioObjects(
            @RequestParam(required = false) String prefix) {
        
        try {
            List<String> objects;
            if (prefix != null && !prefix.trim().isEmpty()) {
                objects = minioService.listObjects(prefix.trim());
            } else {
                objects = minioService.listObjects();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("count", objects.size());
            response.put("objects", objects);
            response.put("prefix", prefix);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取MinIO文件列表失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 检查存储桶状态
     * 
     * @return 存储桶状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            boolean minioExists = minioService.bucketExists();
            boolean ossExists = ossService.doesBucketExist();
            
            status.put("success", true);
            status.put("minio_bucket_exists", minioExists);
            status.put("oss_bucket_exists", ossExists);
            status.put("ready_for_migration", minioExists && ossExists);
            
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            log.error("检查存储桶状态失败", e);
            status.put("success", false);
            status.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(status);
        }
    }
    
    /**
     * 健康检查
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "minio-to-oss");
        health.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(health);
    }
}